controllers.controller('TagToObjectCtrl', ['$rootScope','$scope', '$http', '$q', function($rootScope, $scope, $http, $q) {
    $scope.isCollapsedObjects = true;
    $http(jsRoutes.controllers.TagsController.getAllTags()).success(function(data, status, headers, config) {
        //sababa
        $scope.tags = data;
    }).error(function(data, status, headers, config) {
            alert("error fetching tags")
        });
    $scope.getAllObjects = function() {
        var defferd = $q.defer();
        $http(jsRoutes.controllers.ObjectsController.getAllObjects()).success(function(data, status, headers, config) {
            defferd.resolve(data)
        }).error(function(data, status, headers, config) {
                alert("error fetching objects")
            });

        return defferd.promise;
    }

    $scope.getAllObjects().then(function(data) {
        $scope.objects = data;
    });


    $scope.handleObjectSubmit = function() {
        var deffered = $q.defer();
        $scope.saveObjectPromise = deffered.promise;
        $http.post(jsRoutes.controllers.ObjectsController.saveObject().url, $scope.object).success(function() {
            $scope.object.tag = angular.fromJson($scope.object.tag);
            $scope.object = null;
            //$scope.objects.push($scope.object);
            $scope.getAllObjects().then(function(data) {
                $scope.objects = data;
                $rootScope.$$childTail.successMsg.push('Saved successfully!')
                deffered.resolve();
            });
        }).error(function() {
                deffered.reject();
                console.log("this is error "+arguments)
            });
    }

    $scope.saveObject = function(objs) {
        var deffered = $q.defer();
        $http.post(jsRoutes.controllers.ObjectsController.saveObject().url, objs).success(function() {
            console.log("success");
            objs.changed = false;
            $rootScope.$$childTail.successMsg.push('Saved successfully!');
            deffered.resolve();

        }).error(function() {
                $rootScope.$$childTail.successMsg.push('Error! try again later');
                objs.error = true;
            })

        $scope.saveObjPromise = deffered.promise;
    }
}]);